
#include "log.h"
#include <memory>
#include <iostream>
#include <fstream>
#include <cstring>
#include <ctime>
#include <sstream>
#include <map>
#include <functional>
#include "config.h"
#include "util.h"

namespace sylar
{
    class Logger;
    LogEventWrap::LogEventWrap(std::shared_ptr<class Logger> logger, std::shared_ptr<class LogEvent> event, LogLevel::Level level)
        : m_logger(logger), m_event(event), m_level(level) {}

    LogEventWrap::~LogEventWrap()
    {
        // 析构时自动输出日志
        m_logger->log(m_level, m_event);
    }

    std::stringstream &LogEventWrap::getSS()
    {
        return m_event->getSS();
    }

    class StringFormatItem : public LogFormatter::FormatItem
    {
    public:
        StringFormatItem(const std::string &str) : m_str(str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << m_str;
        }

    private:
        std::string m_str;
    };

    class LevelFormatItem : public LogFormatter::FormatItem
    {
    public:
        LevelFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << LogLevel::ToString(event->getLevel());
        }
    };

    class MessageFormatItem : public LogFormatter::FormatItem
    {
    public:
        MessageFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getContent();
        }
    };

    class ElapseFormatItem : public LogFormatter::FormatItem
    {
    public:
        ElapseFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getElapse();
        }
    };

    class ThreadIdFormatItem : public LogFormatter::FormatItem
    {
    public:
        ThreadIdFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getThreadId();
        }
    };

    class DateTimeFormatItem : public LogFormatter::FormatItem
    {
    public:
        DateTimeFormatItem(const std::string format = "%Y:%m:%d %H:%M:%S") : m_format(format) {} // 修正时间格式符（%N改为%M）

        void format(std::ostream &os, LogEvent::ptr event) override
        {
            time_t t = event->getTime();
            struct tm tm;
            localtime_r(&t, &tm); // 线程安全的时间转换
            char buf[128];
            strftime(buf, sizeof(buf), m_format.c_str(), &tm);
            os << buf;
        }

    private:
        std::string m_format;
    };

    class FiberIdFormatItem : public LogFormatter::FormatItem
    {
    public:
        FiberIdFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getFiberId();
        }
    };

    class FilenameFormatItem : public LogFormatter::FormatItem
    {
    public:
        FilenameFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getFile();
        }
    };

    class LineFormatItem : public LogFormatter::FormatItem
    {
    public:
        LineFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getLine();
        }
    };

    class NewLineFormatItem : public LogFormatter::FormatItem
    {
    public:
        NewLineFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << std::endl;
        }
    };
    class TabFormatItem : public LogFormatter::FormatItem
    {
    public:
        TabFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << "\t";
        }
    };
    class PriorityFormatItem : public LogFormatter::FormatItem
    {
    public:
        PriorityFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << LogLevel::ToString(event->getLevel());
        }
    };
    class ThreadNameFormatItem : public LogFormatter::FormatItem
    {
    public:
        ThreadNameFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getThreadName();
        }
    };
    class PercentSignFormatItem : public LogFormatter::FormatItem
    {
    public:
        PercentSignFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << "%";
        }
    };
    class LoggerNameFormatItem : public LogFormatter::FormatItem
    {
    public:
        LoggerNameFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getLoggerName();
        }
    };
    class FileNameFormatItem : public LogFormatter::FormatItem
    {
    public:
        FileNameFormatItem(const std::string &str) {}
        void format(std::ostream &os, LogEvent::ptr event) override
        {
            os << event->getFile();
        }
    };

    // 原有其他类的实现
    LogFormatter::FormatItem::~FormatItem() {}

    LogAppender::~LogAppender() {}

    Logger::Logger(const std::string &name) : m_name(name)
    {
        // m_formatter.reset(new LogFormatter("%d [ %p ] %f %l %m  %n"));
        setFormatter(std::make_shared<LogFormatter>("%d{%Y-%m-%d %H:%M:%S}%T%N%T[%p]%T%f:%l-%T%m %n"));
    }

    void Logger::addAppender(LogAppender::ptr appender)
    {
        if (!getFormatter())
        {
            m_formatter.reset(new LogFormatter("%d{%Y-%m-%d %H:%M:%S}%T%N%T[%p]%T%f:%l-%T%m %n"));
        }
        m_appenders.push_back(appender);
    }

    void Logger::delAppender(LogAppender::ptr appender)
    {
        for (auto it = m_appenders.begin(); it != m_appenders.end(); ++it)
        {
            if (*it == appender)
            {
                m_appenders.erase(it);
                break;
            }
        }
    }

    void Logger::log(LogLevel::Level level, LogEvent::ptr event)
    {
        if (level >= m_level)
        {
            for (auto &i : m_appenders)
            {
                i->log(event);
            }
        }
        else if (m_root)
        {
            m_root->log(level, event);
        }
    }

    void Logger::debug(LogEvent::ptr event)
    {
        log(LogLevel::DEBUG, event);
    }

    void Logger::info(LogEvent::ptr event)
    {
        log(LogLevel::INFO, event);
    }

    void Logger::warn(LogEvent::ptr event)
    {
        log(LogLevel::WARN, event);
    }

    void Logger::error(LogEvent::ptr event)
    {
        log(LogLevel::ERROR, event);
    }

    void Logger::fatal(LogEvent::ptr event)
    {
        log(LogLevel::FATAL, event);
    }

    FileLogAppender::FileLogAppender(const std::string &filename, uint64_t check_interval)
        : m_filename(filename), m_checkInterval(check_interval), m_lastTime(std::chrono::steady_clock::now())
    {
        m_formatter = std::make_shared<LogFormatter>();
        m_defaultFormatter = std::make_shared<LogFormatter>();

        reopen(); // 初始化时打开文件
    }
    void FileLogAppender::log(LogEvent::ptr event)
    {
        auto cur_time = std::chrono::steady_clock::now();
        // 计算距离上次reopen的时间差（毫秒）
        // 修改后（正确）
        auto elapsed = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(cur_time - m_lastTime).count());
        if (elapsed >= m_checkInterval)
        {
            if (reopen())
            { // 仅在reopen成功后更新时间戳
                m_lastTime = cur_time;
            }
        }

        // 写入日志（加锁保证线程安全）
        MutexType::Lock lock(m_mutex);
        if (event->getLevel() >= m_level && m_filestream.good())
        {
            m_filestream << m_formatter->format(event);
            m_filestream.flush();
        }
    }

    // 假设在FileLogAppender的reopen或构造函数中
    bool FileLogAppender::reopen()
    {
        MutexType::Lock lock(m_mutex);
        if (m_filestream.is_open())
        {
            m_filestream.close();
        }
        // 打开文件（追加模式，不存在则创建）
        m_filestream.open(m_filename, std::ios::app | std::ios::out);
        // 检查打开是否成功
        if (!m_filestream.is_open())
        {
            // 输出错误日志（使用内部日志器）
            SYLAR_LOG_ERROR(SYLAR_ERROR_LOGGER())
                << "FileLogAppender打开文件失败: " << m_filename
                << ", 错误信息: " << strerror(errno);
            return false;
        }
        return true;
    }
    void StdoutLogAppender::log(LogEvent::ptr event)
    {
        MutexType::Lock lock(m_mutex);
        if (event->getLevel() >= m_level)
        {
            std::cout << m_formatter->format(event);
            std::cout.flush();
        }
    }

    LogFormatter::LogFormatter(const std::string &pattern) : m_pattern(pattern)
    {
        init();
    }

    std::string LogFormatter::format(LogEvent::ptr event)
    {
        std::stringstream ss;
        for (auto &i : m_items)
        {
            i->format(ss, event);
        }
        return ss.str();
    }

    void LogFormatter::init()
    {
        // 按顺序存储解析到的pattern项
        // 每个pattern包括一个整数类型和一个字符串，类型为0表示该pattern是常规字符串，为1表示该pattern需要转义
        // 日期格式单独用下面的dataformat存储
        std::vector<std::pair<int, std::string>> patterns;
        // 临时存储常规字符串
        std::string tmp;
        // 日期格式字符串，默认把位于%d后面的大括号对里的全部字符都当作格式字符，不校验格式是否合法
        std::string dateformat;
        // 是否解析出错
        bool error = false;

        // 是否正在解析常规字符，初始时为true
        bool parsing_string = true;
        // 是否正在解析模板字符，%后面的是模板字符
        // bool parsing_pattern = false;
        size_t i = 0;
        while (i < m_pattern.size())
        {
            std::string c = std::string(1, m_pattern[i]);
            if (c == "%")
            {
                if (parsing_string)
                {
                    if (!tmp.empty())
                    {
                        patterns.push_back(std::make_pair(0, tmp));
                    }
                    tmp.clear();
                    parsing_string = false; // 在解析常规字符时遇到%，表示开始解析模板字符
                    // parsing_pattern = true;
                    i++;
                    continue;
                }
                else
                {
                    patterns.push_back(std::make_pair(1, c));
                    parsing_string = true; // 在解析模板字符时遇到%，表示这里是一个%转义
                    // parsing_pattern = false;
                    i++;
                    continue;
                }
            }
            else
            { // not %
                if (parsing_string)
                { // 持续解析常规字符直到遇到%，解析出的字符串作为一个常规字符串加入patterns
                    tmp += c;
                    i++;
                    continue;
                }
                else
                { // 模板字符，直接添加到patterns中，添加完成后，状态变为解析常规字符，%d特殊处理
                    patterns.push_back(std::make_pair(1, c));
                    parsing_string = true;
                    // parsing_pattern = false;

                    // 后面是对%d的特殊处理，如果%d后面直接跟了一对大括号，那么把大括号里面的内容提取出来作为dateformat
                    if (c != "d")
                    {
                        i++;
                        continue;
                    }
                    i++;
                    if (i < m_pattern.size() && m_pattern[i] != '{')
                    {
                        continue;
                    }
                    i++;
                    while (i < m_pattern.size() && m_pattern[i] != '}')
                    {
                        dateformat.push_back(m_pattern[i]);
                        i++;
                    }
                    if (m_pattern[i] != '}')
                    {
                        // %d后面的大括号没有闭合，直接报错
                        std::cout << "[ERROR] LogFormatter::init() " << "pattern: [" << m_pattern << "] '{' not closed" << std::endl;
                        error = true;
                        break;
                    }
                    i++;
                    continue;
                }
            }
        } // end while(i < m_pattern.size())

        if (error)
        {
            m_error = true;
            return;
        }

        // 模板解析结束之后剩余的常规字符也要算进去
        if (!tmp.empty())
        {
            patterns.push_back(std::make_pair(0, tmp));
            tmp.clear();
        }

        // for debug
        // std::cout << "patterns:" << std::endl;
        // for(auto &v : patterns) {
        //     std::cout << "type = " << v.first << ", value = " << v.second << std::endl;
        // }
        // std::cout << "dataformat = " << dateformat << std::endl;

        static std::map<std::string, std::function<FormatItem::ptr(const std::string &str)>> s_format_items = {
#define XX(str, C)                                                               \
    {                                                                            \
        #str, [](const std::string &fmt) { return FormatItem::ptr(new C(fmt)); } \
    }

            XX(m, MessageFormatItem),     // m:消息
            XX(p, LevelFormatItem),       // p:日志级别
            XX(c, LoggerNameFormatItem),  // c:日志器名称
            XX(d, DateTimeFormatItem),    // d:日期时间
            XX(e, ElapseFormatItem),      // r:累计毫秒数
            XX(f, FileNameFormatItem),    // f:文件名
            XX(l, LineFormatItem),        // l:行号
            XX(t, ThreadIdFormatItem),    // t:编程号
            XX(F, FiberIdFormatItem),     // F:协程号
            XX(N, ThreadNameFormatItem),  // N:线程名称
            XX(%, PercentSignFormatItem), // %:百分号
            XX(T, TabFormatItem),         // T:制表符
            XX(n, NewLineFormatItem),     // n:换行符
                                          //             XX(d, DateTimeFormatItem),
//             XX(t, ThreadIdFormatItem),
//             XX(f, FilenameFormatItem),
//             XX(l, LineFormatItem),
//             XX(m, MessageFormatItem),
//             XX(n, NewLineFormatItem),
//             XX(e, ElapseFormatItem),
//             XX(F, FiberIdFormatItem),
//             XX(T, TabFormatItem),
//             XX(p, LevelFormatItem)};
#undef XX
        };

        for (auto &v : patterns)
        {
            if (v.first == 0)
            {
                m_items.push_back(FormatItem::ptr(new StringFormatItem(v.second)));
            }
            else if (v.second == "d")
            {
                m_items.push_back(FormatItem::ptr(new DateTimeFormatItem(dateformat)));
            }
            else
            {
                auto it = s_format_items.find(v.second);
                if (it == s_format_items.end())
                {
                    std::cerr << "[ERROR] LogFormatter::init() " << "pattern: [" << m_pattern << "] " << "unknown format item: " << v.second << std::endl;
                    error = true;
                    break;
                }
                else
                {
                    m_items.push_back(it->second(v.second));
                }
            }
        }

        if (error)
        {
            m_error = true;

            P("init error()  \n");
            return;
        }
    }

    const char *LogLevel::ToString(LogLevel::Level level)
    {
        switch (level)
        {
#define XX(name)         \
    case LogLevel::name: \
        return #name;
            XX(FATAL);
            XX(ALERT);
            XX(CRIT);
            XX(ERROR);
            XX(WARN);
            XX(NOTICE);
            XX(INFO);
            XX(DEBUG);
            XX(UNKNOWN);
#undef XX
        default:
            return "NOTSET";
        }
        return "NOTSET";
    }
    LogLevel::Level LogLevel::FromString(const std::string &str)
    {
#define XX(level, v)            \
    if (str == #v)              \
    {                           \
        return LogLevel::level; \
    }
        XX(FATAL, fatal);
        XX(ALERT, alert);
        XX(CRIT, crit);
        XX(ERROR, error);
        XX(WARN, warn);
        XX(NOTICE, notice);
        XX(INFO, info);
        XX(DEBUG, debug);
        XX(UNKNOWN, unknown);

        XX(FATAL, FATAL);
        XX(ALERT, ALERT);
        XX(CRIT, CRIT);
        XX(ERROR, ERROR);
        XX(WARN, WARN);
        XX(NOTICE, NOTICE);
        XX(INFO, INFO);
        XX(DEBUG, DEBUG);
        XX(UNKNOWN, UNKNOWN);
#undef XX

        return LogLevel::NOTSET;
    }

    // 初始化默认日志器的通用函数（减少重复代码）
    static Logger::ptr createDefaultLogger(const std::string &name, LogLevel::Level level)
    {
        Logger::ptr logger = std::make_shared<Logger>(name);
        logger->setLevel(level);
        // 添加标准输出Appender
        StdoutLogAppender::ptr stdout_appender = std::make_shared<StdoutLogAppender>();
        stdout_appender->setFormatter(std::make_shared<LogFormatter>(
            "%d{%Y-%m-%d %H:%M:%S}%T%N%T[%p]%T%f:%l-%T%m %n"));
        logger->addAppender(stdout_appender);

        return logger;
    }

    // 构造函数：初始化所有默认日志器并检查指针
    LoggerManager::LoggerManager()
    {
        m_infoLogger = createDefaultLogger("info", LogLevel::INFO);
        // 初始化各级别日志器
        m_root = createDefaultLogger("root", LogLevel::WARN);
        m_debugLogger = createDefaultLogger("debug", LogLevel::DEBUG);
        m_warnLogger = createDefaultLogger("warn", LogLevel::WARN);
        m_errorLogger = createDefaultLogger("error", LogLevel::ERROR);
        m_fatalLogger = createDefaultLogger("fatal", LogLevel::FATAL);

        // SELF_LOG：检查日志器指针有效性（使用已初始化的infoLogger输出检查日志）
        if (!m_infoLogger)
        {
            // 极端情况：infoLogger自身为空，使用标准错误输出
            std::cerr << "SELF_LOG: 初始化infoLogger失败！" << std::endl;
        }
        else
        {
            SYLAR_LOG_FMT_INFO(m_infoLogger, "SELF_LOG: infoLogger初始化成功");
        }
        if (!m_root)
        {
            SYLAR_LOG_FMT_ERROR(m_infoLogger, "SELF_LOG: 初始化warnLogger失败！");
        }
        else
        {
            SYLAR_LOG_FMT_INFO(m_infoLogger, "SELF_LOG: root:warnLogger初始化成功");
        }
        if (!m_debugLogger)
        {
            SYLAR_LOG_FMT_ERROR(m_infoLogger, "SELF_LOG: 初始化debugLogger失败！");
        }
        else
        {
            SYLAR_LOG_FMT_INFO(m_infoLogger, "SELF_LOG: debugLogger初始化成功");
        }

        if (!m_warnLogger)
        {
            SYLAR_LOG_FMT_ERROR(m_infoLogger, "SELF_LOG: 初始化warnLogger失败！");
        }
        else
        {
            SYLAR_LOG_FMT_INFO(m_infoLogger, "SELF_LOG: warnLogger初始化成功");
        }

        if (!m_errorLogger)
        {
            SYLAR_LOG_FMT_ERROR(m_infoLogger, "SELF_LOG: 初始化errorLogger失败！");
        }
        else
        {
            SYLAR_LOG_FMT_INFO(m_infoLogger, "SELF_LOG: errorLogger初始化成功");
        }

        if (!m_fatalLogger)
        {
            SYLAR_LOG_FMT_ERROR(m_infoLogger, "SELF_LOG: 初始化fatalLogger失败！");
        }
        else
        {
            SYLAR_LOG_FMT_INFO(m_infoLogger, "SELF_LOG: fatalLogger初始化成功");
        }
    }
    template <>
    class LexicalCast<std::string, LogLevel::Level>
    {
    public:
        LogLevel::Level operator()(const std::string &str)
        {

            return LogLevel::FromString(str);
        }
    };

    //     int type = 0;
    // sylar::LogLevel::Level level = sylar::LogLevel::UNKNOWN;
    // std::string formatter;
    // std::string file;
    template <>
    class LexicalCast<LogLevel::Level, std::string>
    {
    public:
        std::string operator()(const LogLevel::Level &vec)
        {
            return static_cast<std::string>(LogLevel::ToString(vec));
        }
    };

    //     std::string name;
    // sylar::LogLevel::Level level = sylar::LogLevel::UNKNOWN;
    // std::string formatter;
    // std::vector<LogAppenderDefine> appenders;

    class LogAppenderDefine
    {
    public:
        int type = 0;
        LogLevel::Level level = LogLevel::NOTSET;
        std::string formatter;
        std::string file;

        bool operator==(const LogAppenderDefine &other) const
        {
            return type == other.type && level == other.level && formatter == other.formatter && file == other.file;
        }

        bool operator<(const LogAppenderDefine &other) const
        {
            if (type != other.type)
                return type < other.type;
            if (level != other.level)
                return level < other.level;
            if (file != other.file)
                return file < other.file;
            return formatter < other.formatter;
        }
    };

    class LogDefine
    {
    public:
        std::string name;
        LogLevel::Level level = LogLevel::NOTSET;
        std::string formatter;
        std::vector<LogAppenderDefine> appenders;

        bool operator==(const LogDefine &other) const
        {
            return name == other.name && level == other.level && formatter == other.formatter && appenders == other.appenders;
        }

        bool operator<(const LogDefine &other) const
        {
            return name < other.name;
        }
        bool isValid() const
        {
            return !name.empty();
        }
    };
    ConfigVar<std::set<LogDefine>>::ptr g_log_define =
        Config::Lookup("logs", std::set<LogDefine>(), "logs config");

    template <>
    class LexicalCast<std::string, LogDefine>
    {
    public:
        LogDefine operator()(const std::string &v)
        {
            YAML::Node n = YAML::Load(v);
            LogDefine ld;
            if (!n["name"].IsDefined())
            {
                std::cout << "log config error: name is null, " << n << std::endl;
                throw std::logic_error("log config name is null");
            }
            ld.name = n["name"].as<std::string>();
            ld.level = LogLevel::FromString(n["level"].IsDefined() ? n["level"].as<std::string>() : "");

            if (n["appenders"].IsDefined())
            {
                for (size_t i = 0; i < n["appenders"].size(); i++)
                {
                    auto a = n["appenders"][i];
                    if (!a["type"].IsDefined())
                    {
                        std::cout << "log appender config error: appender type is null, " << a << std::endl;
                        continue;
                    }
                    std::string type = a["type"].as<std::string>();
                    LogAppenderDefine lad;
                    if (type == "FileLogAppender")
                    {
                        lad.type = 1;
                        if (!a["file"].IsDefined())
                        {
                            std::cout << "log appender config error: file appender file is null, " << a << std::endl;
                            continue;
                        }
                        lad.file = a["file"].as<std::string>();
                        if (a["formatter"].IsDefined())
                        {
                            lad.formatter = a["formatter"].as<std::string>();
                        }
                    }
                    else if (type == "StdoutLogAppender")
                    {
                        lad.type = 2;
                        if (a["formatter"].IsDefined())
                        {
                            lad.formatter = a["formatter"].as<std::string>();
                        }
                    }
                    else
                    {
                        std::cout << "log appender config error: appender type is invalid, " << a << std::endl;
                        continue;
                    }
                    if (a["level"].IsDefined())
                    {
                        lad.level = LogLevel::FromString(a["level"].as<std::string>());
                    }
                    ld.appenders.push_back(lad);
                }
            } // end for
            return ld;
        }
    };

    template <>
    class LexicalCast<LogDefine, std::string>
    {
    public:
        std::string operator()(const LogDefine &i)
        {
            YAML::Node n;
            n["name"] = i.name;
            n["level"] = LogLevel::ToString(i.level);
            for (auto &a : i.appenders)
            {
                YAML::Node na;
                if (a.type == 1)
                {
                    na["type"] = "FileLogAppender";
                    na["file"] = a.file;
                }
                else if (a.type == 2)
                {
                    na["type"] = "StdoutLogAppender";
                }
                if (!a.formatter.empty())
                {
                    na["formatter"] = a.formatter;
                }
                n["appenders"].push_back(na);
            }
            std::stringstream ss;
            ss << n;
            return ss.str();
        }
    };
    struct LogIniter
    {
        LogIniter()
        {
            P("LogIniter");
            g_log_define->addListener([](const std::set<LogDefine> &old_value,
                                         const std::set<LogDefine> &new_value)
                                      {
            // 配置开始更新时输出调试信息
            S() << "开始处理日志配置更新，旧配置大小: " << old_value.size()
                << ", 新配置大小: " << new_value.size();
            S() << "config update";

            // 处理新配置中的日志器
            for(auto& i : new_value) {
                S() << "处理新配置日志器: " << i.name
                    << ", 级别: " << LogLevel::ToString(i.level);

                auto it = old_value.find(i);
                Logger::ptr logger;

                if(it == old_value.end()) {
                    // 新建日志器
                    logger.reset(new Logger(i.name));
                    LoggerManager::GetInstance()->addLogger(logger->getName(), logger);
                    S() << "创建新日志器: " << i.name
                        << ", 添加到管理器";
                } else {
                    if(!(i == *it)) {
                        // 修改已有日志
                        logger = SYLAR_LOG_NAME(i.name);
                        S() << "修改已有日志器: " << i.name
                            << ", 旧配置与新配置不一致";
                    } else {
                        // 配置未变更，跳过
                        S() << "日志器 " << i.name << " 配置未变更，跳过处理";
                        continue;
                    }
                }

                // 设置日志级别
                logger->setLevel(i.level);
                S() << "日志器 " << i.name
                    << " 设置级别为: " << LogLevel::ToString(i.level)
                    << "（数值：" << (int)i.level << "）";

                // 设置格式器
                if(!i.formatter.empty()) {
                    logger->setFormatter(i.formatter);
                    S() << "日志器 " << i.name
                        << " 设置格式: " << i.formatter;
                } else {
                    S() << "日志器 " << i.name
                        << " 未设置格式器，使用默认格式";
                }

                // 清理并重新添加Appender
                logger->clearAppenders();
                S() << "日志器 " << i.name << " 清空旧Appender（当前Appender数量："
                    << logger->getAppenders().size() << "）";

                // 处理当前日志器的所有Appender配置
                S() << "日志器 " << i.name << " 开始处理 "
                    << i.appenders.size() << " 个Appender配置";
                for(size_t idx = 0; idx < i.appenders.size(); ++idx) {
                    auto& a = i.appenders[idx];
                    S() << "处理第 " << idx+1 << " 个Appender配置："
                        << " 类型=" << a.type
                        << " 级别=" << LogLevel::ToString(a.level)
                        << "（数值：" << (int)a.level << "）"
                        << " 文件路径=" << (a.type == 1 ? a.file : "无");

                    LogAppender::ptr ap;
                    if(a.type == 1) {
                        // 创建文件Appender
                        ap.reset(new FileLogAppender(a.file));
                        // 验证文件Appender是否创建成功
                        if(!ap) {
                            S() << "日志器 " << i.name
                                << " 创建文件Appender失败（路径：" << a.file << "）";
                            continue;
                        }
                        // 尝试打开文件并检查结果
                        bool open_success = std::dynamic_pointer_cast<FileLogAppender>(ap)->reopen();
                        S() << "为 " << i.name << " 创建文件Appender（路径：" << a.file
                            << "），打开结果：" << (open_success ? "成功" : "失败");
                        if(!open_success) {
                            S() << "文件Appender打开失败，可能原因：路径不存在或权限不足（" << a.file << "）";
                        }
                    } else if(a.type == 2) {
                        // 创建标准输出Appender
                        ap.reset(new StdoutLogAppender());
                        if(!ap) {
                            S() << "日志器 " << i.name << " 创建标准输出Appender失败";
                            continue;
                        }
                        S() << "为 " << i.name << " 创建标准输出Appender成功";
                    } else {
                        S() << "日志器 " << i.name
                            << " 遇到未知Appender类型（" << a.type << "），跳过该Appender";
                        continue;
                    }

                    // 设置Appender级别
                    ap->setLevel(a.level);
                    S() << "Appender级别设置为: " << LogLevel::ToString(a.level)
                        << "（数值：" << (int)a.level << "），当前实际级别："
                        << LogLevel::ToString(ap->getLevel())
                        << "（数值：" << (int)ap->getLevel() << "）";

                    // 为Appender设置格式器（如果配置了）
                    if(!a.formatter.empty()) {
                        ap->setFormatter(a.formatter);
                        S() << "Appender设置格式: " << a.formatter;
                    }

                    // 添加Appender到日志器
                    logger->addAppender(ap);
                    // 验证添加结果
                    if(logger->getAppenders().size() > idx) {
                        S() << "Appender添加到日志器 " << i.name << " 成功，当前Appender总数："
                            << logger->getAppenders().size();
                    } else {
                        S() << "Appender添加到日志器 " << i.name << " 失败";
                    }
                }
            }

            // 处理需要删除的日志器（旧配置有，新配置无）
            for(auto& i : old_value) {
                auto it = new_value.find(i);
                if(it == new_value.end()) {
                    // 删除日志器
                    auto logger = SYLAR_LOG_NAME(i.name);
                    logger->setLevel((LogLevel::Level)100);
                    logger->clearAppenders();
                    S() << "删除日志器: " << i.name
                        << "（设置级别为100并清空Appender）";
                }
            }

            S() << "日志配置更新处理完成"; });
        }
    };
    static LogIniter __log_init;

} // namespace sylar
